//
//  GTCategoryViewController.m
//  GiftTalk
//
//  Created by Wan on 16/4/12.
//  Copyright © 2016年 Wan. All rights reserved.
//

#import "GTCategoryViewController.h"
#import <MJRefresh.h>
#import <MJExtension.h>
#import "GTNetWorkManager.h"
#import <View+MASAdditions.h>
#import "GTSubCategoryCell.h"
#import "GTSubCategoryHeaderView.h"
#import "GTProgressHUDManager.h"
#import "GTCategory.h"
#import "GTSubCategory.h"
#import "GTCategoryCell.h"
#import "GTSubCategoryCell.h"
#import "GTGiftItemViewController.h"

@interface GTCategoryViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate>

/** 礼物类别 */
@property (strong, nonatomic) NSArray *categories;
/** netWorkTool */
@property (strong, nonatomic) GTNetWorkManager *shareNetWorkTool;

/** 左边分类列表 */
@property (weak, nonatomic) UITableView *categoryTableView;
/** 右边礼物列表 */
@property (weak, nonatomic) UICollectionView *subCategoryCollectionView;

/************** 辅助属性 ************/
@property (assign, nonatomic) BOOL categoriesSelectedFlag;
@property (assign, nonatomic, getter=isDown) BOOL down;

@end

@implementation GTCategoryViewController

- (GTNetWorkManager *)shareNetWorkTool {
    if (!_shareNetWorkTool) {
        _shareNetWorkTool = [GTNetWorkManager shareNetWorkTool];
    }
    return _shareNetWorkTool;
}

- (NSArray *)categories {
    if (!_categories) {
        _categories = [NSArray array];
    }
    return _categories;
}

#pragma mark - Lift Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self buildCategoryTableView];
    
    [self buildSubCategoryCollectionView];
    
    [self loadCategoryData];
}


#pragma mark - Create UI

- (void)buildCategoryTableView {
    
    UITableView *categoryTablView = [[UITableView alloc] init];
    categoryTablView.dataSource = self;
    categoryTablView.delegate = self;
    categoryTablView.showsVerticalScrollIndicator = NO;
    categoryTablView.rowHeight = 40; /* bugfix：iphone5下高度不正确 */
    [self.view addSubview:categoryTablView];
    categoryTablView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.categoryTableView = categoryTablView;
    
    // 添加位置约束
    [categoryTablView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(64);
        make.width.equalTo(@100.0);
        make.bottom.equalTo(self.view).offset(-46);
    }];
}

- (void)buildSubCategoryCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    UICollectionView *subCategoryCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    [self.view addSubview:subCategoryCollectionView];
    self.subCategoryCollectionView = subCategoryCollectionView;
    
    subCategoryCollectionView.dataSource = self;
    subCategoryCollectionView.delegate = self;
    subCategoryCollectionView.contentInset = UIEdgeInsetsMake(0, 0, 46, 0);
    
    [subCategoryCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(64);
        make.left.equalTo(self.categoryTableView.mas_right);
    }];
    
    self.subCategoryCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadCategoryData)];
    
    /** 注册礼物 cell &  cell 头部视图 */
    // 通过Class 注册生成cell，viewCell需要继承 UICollectionViewCell
    [self.subCategoryCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GTSubCategoryCell class]) bundle:nil] forCellWithReuseIdentifier:subCategoryIdentifier];
    //注册headerView, Nib的view需要继承UICollectionReusableView
    [self.subCategoryCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GTSubCategoryHeaderView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reuseHeaderIdentifier];
    self.subCategoryCollectionView.backgroundColor = [UIColor whiteColor];
    
    // item 之间的最小间距
    flowLayout.minimumInteritemSpacing = GTSearchGiftCellMargin;
    flowLayout.sectionInset = GTTableViewCellUIEdgeInsets;
    
    // item行间距 & item间距 设置（最小值）
    flowLayout.minimumLineSpacing = GTSubCategoryLineSpacing;
    flowLayout.minimumInteritemSpacing = GTSubCategoryInteritemSpacing;
    flowLayout.sectionInset = GTSubCategorySectionInset;
    
    // 头部视图参考尺寸
    flowLayout.headerReferenceSize = CGSizeMake(self.subCategoryCollectionView.width, 44);
    // 每个 cell 的大小
    CGFloat itemW = (GTScreenW * 0.75 - 5 * GTSubCategoryInteritemSpacing) * 0.25;
    CGFloat itemH = itemW * 1.5;
    flowLayout.itemSize = CGSizeMake(itemW, itemH);
    
    [self.subCategoryCollectionView layoutIfNeeded];
}

- (void)loadCategoryData {
    NSString *urlStr = @"v2/item_categories/tree?";
    
    if (self.categories.count > 0) {
        [self.subCategoryCollectionView.mj_header endRefreshing];
    }
    [GTProgressHUDManager showWithStatus:@"正在加载中..."];
    
    [self.shareNetWorkTool GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [SVProgressHUD dismiss];
        
        self.categories = [GTCategory mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"categories"]];
        
        self.categoryTableView.mj_header.hidden = YES;
        [self.categoryTableView reloadData];
        [self.subCategoryCollectionView reloadData];
        
        // 默认设置为YES，以让默认选中第一行生效
        self.down = YES;
        
        // 加载完成，选中第一行
        [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:error.description];
        [self.categoryTableView.mj_header endRefreshing];
    }];

}


#pragma mark - <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.categories.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    GTCategory *category = self.categories[section];
    return category.subcategories.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GTCategory *category = self.categories[indexPath.section];
    GTSubCategory *subCategory = category.subcategories[indexPath.row];
    GTSubCategoryCell *cell = [GTSubCategoryCell cellWithCollectionView:collectionView forIndexPath:indexPath];
    cell.subCategory = subCategory;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    GTSubCategoryHeaderView *reusableView = [GTSubCategoryHeaderView reuseViewWithCollectionView:collectionView forIndexPath:indexPath];
    GTCategory *category = self.categories[indexPath.section];
    reusableView.category = category;
    
    return reusableView;
}

#pragma mark - <UICollectionViewDelegate>

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.categoriesSelectedFlag == YES) return;
    
    GTCategory *category = self.categories[indexPath.section];
    
    // 有一半展示出来，并且向上滚时才更改tableView的选中cell
    if (indexPath.row == category.subcategories.count / 2 && !self.isDown) {
        // 展示的是当前的section
        NSInteger section = indexPath.section;
        section = MIN(MAX(0, section), self.categories.count - 2);
        NSIndexPath *categoryIndexPath = [NSIndexPath indexPathForRow:section inSection:0];
        [self.categoryTableView selectRowAtIndexPath:categoryIndexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    GTCategory *category = self.categories[indexPath.section];
//    GTLog(@"%zd---%zd",indexPath.row,category.subcategories.count);
    if (self.categoriesSelectedFlag == YES) return;
    
    // 最后一个item消失并且向下滚时，才更改tableView的选中cell
    if (indexPath.row == category.subcategories.count - 1 && self.isDown) {
        // 消失的是上一个section，所以加1
        NSInteger section = indexPath.section + 1;
        section = MIN(MAX(0, section), self.categories.count - 2);
        NSIndexPath *categoryIndexPath = [NSIndexPath indexPathForRow:section inSection:0];
        [self.categoryTableView selectRowAtIndexPath:categoryIndexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    GTCategory *category = self.categories[indexPath.section];
    GTSubCategory *subCategory = category.subcategories[indexPath.row];
    GTGiftItemViewController *itemVc = [[GTGiftItemViewController alloc] init];
    itemVc.firstPageURLString = [self subCategoryURLWithNumber:subCategory.ID];
    itemVc.title = subCategory.name;
    [self.navigationController pushViewController:itemVc animated:YES];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.categories.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GTCategoryCell *cell = [GTCategoryCell cellWithTableView:tableView];
    GTCategory *category = self.categories[indexPath.row];
    cell.category = category;
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSIndexPath *subCategoryIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
    [self.subCategoryCollectionView selectItemAtIndexPath:subCategoryIndexPath animated:YES scrollPosition: UICollectionViewScrollPositionTop];
    
    // 点击tableView时，让collectionView不能影响tableView的选中行
    self.categoriesSelectedFlag = YES;
}


#pragma mark - <UIScrollViewDelegate>

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 手动滚动右边时，让collectionView决定tableVew的选中行
    self.categoriesSelectedFlag = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 一定要判断，难怪前面出了那么多bug，fuck！
    if ([scrollView isKindOfClass:[UICollectionView class]]) {
        static CGFloat previousOffsetY = 0;
        self.down = previousOffsetY <= scrollView.contentOffset.y;
        previousOffsetY = scrollView.contentOffset.y;
        
        // collectionView底部再下拉50，就选中tableView最后一个cell
        if (scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.height + scrollView.contentInset.bottom + 40) {
            self.categoriesSelectedFlag = YES;
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.categories.count - 1 inSection:0];
            [self.categoryTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
        }
    }
}

#pragma mark - Other Func

- (NSString *)subCategoryURLWithNumber:(NSInteger)number
{
    NSMutableString *channelURL = [NSMutableString stringWithString:@"http://api.liwushuo.com/v2/item_subcategories/"];
    [channelURL appendFormat:@"%ld", number];
    [channelURL appendString:@"/items?limit=20&offset=0"];
    
    return channelURL;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
